<script lang="ts" setup>
import ContentFlowExhibitor from '@/views/ContentFlowExhibitor.vue'
import Banner from '@/components/Banner.vue'
import Sidebar from '@/components/Sidebar.vue'
import LoginForm from '@/components/LoginForm.vue'
import { useArticleStore } from '@/stores/ArticleStore'
import { Message } from '@/dto/Message'
import { onBeforeMount, onMounted, provide, type Ref, ref, watch } from 'vue'
import { ApplicationStatusCodeEnum } from '@/enum/ApplicationStatusCodeEnum'
import type { UserDisplayInformationDto } from '@/dto/UserDisplayInformationDto'
import { microServiceHttpServer } from '@/apis/MicroServiceHttpServer'
import { ossResourceServer } from '@/apis/OssResourceServer'
import {useLoginStore} from '@/stores/login'

const screenSizeLevel = ref(3) as Ref<number>;
const mainEl = ref(null) as Ref<HTMLElement | null>;
const isFormVisible = ref(false) as Ref<boolean>;
const isLoginSuccess = ref(false);
const isUserAvailable = ref(false);
const userData = ref(null);

const mainWrapper = ref('3 / -1');
const loginStore = useLoginStore();
let formCloseControlFlag = false;
provide('screenSizeLevel', screenSizeLevel)
provide('isLoginSuccess', isLoginSuccess)


function responseToWidth() {
  if (window.innerWidth <= 1024) {
    screenSizeLevel.value = 1
    mainEl.value.style = 'grid-template-areas: \'M M M M M M M M M M M M\''

    mainWrapper.value = '2 / -1'
  } else if (window.innerWidth > 1024 && window.innerWidth < 1380) {
    screenSizeLevel.value = 2
    mainEl.value.style = 'grid-template-areas: \'M M M M M M M M R R R R\''

    mainWrapper.value = '2 / -1'
  } else {
    screenSizeLevel.value = 3
    mainEl.value.style = 'grid-template-areas: \'L L M M M M M R R R\''

    mainWrapper.value = '3 / -1'
  }
}
function tryLogoutIfLoginAndTryLoginIfLogout() {
  if (!isLoginSuccess.value) {
    isFormVisible.value = true
    formCloseControlFlag = true
    setTimeout(() => {
      formCloseControlFlag = false
    }, 800)
  } else {
    microServiceHttpServer.performLogout().then(response => {
      let msg = JSON.parse(response.data)
      if (msg.code === ApplicationStatusCodeEnum.OK) {
        console.log('logout success')
      }
      onLogoutSuccess()
    })
  }
}
function onCloseForm() {
  if (formCloseControlFlag) {
    return
  }
  isFormVisible.value = false
}
function onLogoutSuccess(){
  isLoginSuccess.value = false
  loginStore.$patch({
    isLogin:false
  })
}
function onLoginSuccess() {
  isFormVisible.value = false
  isLoginSuccess.value = true
  loginStore.$patch({
    user: userData.value,
    isLogin : true,
  })
}
function formNotifiedLoginSuccess(){
  isLoginSuccess.value = true
  tryLogin()
  onLoginSuccess()
}
function formNotifiedRegisterSuccess(){
  isLoginSuccess.value = true
}
function formNotifiedRegisterFinish(){
  isFormVisible.value = false
  tryLogin()
}
function tryLogin() {
  if (!isUserAvailable.value) {
    microServiceHttpServer.getAuthenticatedUserInfo().then(response => {
      let message: Message<UserDisplayInformationDto> = JSON.parse(response.data)
      if (message.code === ApplicationStatusCodeEnum.NEED_AUTHENTICATION) {
        onLoginFailure();
        return Promise.reject('还么有登录哦')
      } else if (message.code === ApplicationStatusCodeEnum.OK) {
        if (message.data) {
          userData.value = message.data
          isUserAvailable.value = true
          onLoginSuccess()
          return ossResourceServer.getOssResource(userData.value.avatar)
        } else {
          return Promise.reject('用户数据请求失败')
        }
      } else
        return Promise.reject('用户数据请求失败')
    }).then((resposne)=>{
      loginStore.$patch({
        avatar:URL.createObjectURL(new Blob([resposne.data]))
      })
    }, (reason) => {
      console.log(reason)
    })
  }
}
function onLoginFailure(){
  isLoginSuccess.value = false
}
onBeforeMount(() => {
  tryLogin()
  if (!isUserAvailable.value) {
    watch(isLoginSuccess, (value, oldValue, onCleanup) => {
      if (value && !oldValue) {
        tryLogin()
      }else if(!value && oldValue){
        // 退出登录
      }
    })
  } else {
    isLoginSuccess.value = true
  }
})
onBeforeMount(function() {
  microServiceHttpServer.getTopNArticles()
    .then(function(response, error) {
      useArticleStore().$patch((state) => {
        state.hotArticles = JSON.parse(response.data)
      })
    })
})
onMounted(responseToWidth)
window.onresize = responseToWidth
</script>


<template>
  <div class="exhibitor__wrapper snapping__item">
    <content-flow-exhibitor></content-flow-exhibitor>
  </div>
  <div class="snapping__item landing__page__wrapper">


    <sidebar @loginlogout="tryLogoutIfLoginAndTryLoginIfLogout"></sidebar>
    <banner class="banner" />

    <main class="main__wrapper" ref="mainEl" style="grid-template-areas: 'L L  M M M M M R R R'">
      <router-view class="main__wrapper__left" name="mainLeftSide" v-if="screenSizeLevel === 3" />
      <router-view name="main" class="main__wrapper__middle" />
      <router-view class="main__wrapper__right" name="mainRightSide" v-if="screenSizeLevel !== 1"/>
      <div class="bg__relative__root">
        <video id="main__wrapper__bg" loop autoplay>
          <source src="/Background/lamp.webm" type="video/webm" />
          <source src="/Background/lamp.mp4" type="video/mp4" />
        </video>
      </div>
    </main>

    <transition>
      <login-form v-show="isFormVisible"
                  @close-form="onCloseForm"
                  @login-success="formNotifiedLoginSuccess"
                  @register-success="formNotifiedRegisterSuccess"
              @register-finished="formNotifiedRegisterFinish"/>
    </transition>

  </div>
</template>

<style lang="scss">
.snapping__item {
  scroll-snap-align: start;
  scroll-snap-stop: always;
}

.exhibitor__wrapper {
  display: grid;
}

.banner {
  grid-column: v-bind(mainWrapper);
  gap: 0;
}

.landing__page__wrapper {
  display: grid;
  position: relative;
  grid-template-columns: repeat(12, 1fr);
  grid-column-gap: var(--spacing-xs);
  grid-template-rows: 700px 1fr;
}

.main__wrapper {
  position: relative;
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: cover;
  padding-top: var(--spacing-xs);
}

.bg__relative__root {
  position: absolute;
  height: 100%;
  width: 100%;
  z-index: -1;
}

#main__wrapper__bg {
  top: 0;
  position: sticky;
  width: 100%;
  height: 100vh;
  object-fit: cover;
}


.main__wrapper {
  display: grid;
  grid-column: v-bind(mainWrapper);
  grid-template-columns: subgrid;

  .main__wrapper__left {
    grid-area: L;
    margin-left: var(--spacing-xs);
  }

  .main__wrapper__middle {
    column-count: 6;
    grid-area: M;
  }

  .main__wrapper__right {
    grid-area: R;
  }
}


</style>


<style lang="scss">

</style>


<style lang="scss">

</style>

